package com.logistics.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.logistics.common.Constants;
import com.logistics.common.SiteContextHolder;
import com.logistics.dto.DispatchVehicleInfo;
import com.logistics.entity.TransportOrder;
import com.logistics.mapper.TransportOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 发车管理服务
 */
@Service
public class DispatchService {

    @Autowired
    private TransportOrderMapper orderMapper;

    /**
     * 获取发车管理数据
     */
    public Map<String, List<DispatchVehicleInfo>> getDispatchVehicles() {
        String currentUserRole = getCurrentUserRole();
        Long currentSiteId = SiteContextHolder.getSiteId();

        // 构建查询条件
        LambdaQueryWrapper<TransportOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TransportOrder::getOrderStatus, Constants.OrderStatus.LOADED, Constants.OrderStatus.TRANSPORTING)
                .isNotNull(TransportOrder::getVehicleId)
                .isNotNull(TransportOrder::getDriverId);

        // 站点隔离：SITE_ADMIN 只能看本站点的订单
        if ("SITE_ADMIN".equals(currentUserRole) && currentSiteId != null) {
            queryWrapper.eq(TransportOrder::getSiteId, currentSiteId);
        }

        List<TransportOrder> orders = orderMapper.selectList(queryWrapper);

        // 按车辆分组
        Map<String, List<TransportOrder>> vehicleOrdersMap = orders.stream()
                .collect(Collectors.groupingBy(order -> order.getVehicleId() + "_" + order.getVehiclePlate()));

        List<DispatchVehicleInfo> waitingDispatch = new ArrayList<>();
        List<DispatchVehicleInfo> dispatched = new ArrayList<>();

        for (Map.Entry<String, List<TransportOrder>> entry : vehicleOrdersMap.entrySet()) {
            List<TransportOrder> vehicleOrders = entry.getValue();
            TransportOrder firstOrder = vehicleOrders.get(0);

            DispatchVehicleInfo vehicleInfo = new DispatchVehicleInfo();
            vehicleInfo.setVehicleId(firstOrder.getVehicleId());
            vehicleInfo.setVehiclePlate(firstOrder.getVehiclePlate());
            vehicleInfo.setDriverId(firstOrder.getDriverId());
            vehicleInfo.setDriverName(firstOrder.getDriverName());
            vehicleInfo.setDriverPhone(firstOrder.getDriverPhone());
            vehicleInfo.setOrderCount(vehicleOrders.size());

            // 判断车辆状态
            boolean isDispatched = vehicleOrders.stream()
                    .allMatch(order -> Constants.OrderStatus.TRANSPORTING.equals(order.getOrderStatus()));

            if (isDispatched) {
                vehicleInfo.setStatus("TRANSPORTING");
                vehicleInfo.setDispatchedAt(firstOrder.getDispatchedAt());
                dispatched.add(vehicleInfo);
            } else {
                vehicleInfo.setStatus("LOADED");
                waitingDispatch.add(vehicleInfo);
            }

            // 转换订单信息
            List<DispatchVehicleInfo.DispatchOrderInfo> orderInfos = vehicleOrders.stream()
                    .map(this::convertToOrderInfo)
                    .collect(Collectors.toList());
            vehicleInfo.setOrders(orderInfos);
        }

        Map<String, List<DispatchVehicleInfo>> result = new HashMap<>();
        result.put("waitingDispatch", waitingDispatch);
        result.put("dispatched", dispatched);
        return result;
    }

    /**
     * 执行发车操作
     */
    @Transactional
    public int dispatchVehicle(Long vehicleId) {
        String currentUserRole = getCurrentUserRole();
        Long currentSiteId = SiteContextHolder.getSiteId();

        // 查询该车辆的所有LOADED状态订单
        LambdaQueryWrapper<TransportOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TransportOrder::getVehicleId, vehicleId)
                .eq(TransportOrder::getOrderStatus, Constants.OrderStatus.LOADED);

        // 站点隔离
        if ("SITE_ADMIN".equals(currentUserRole) && currentSiteId != null) {
            queryWrapper.eq(TransportOrder::getSiteId, currentSiteId);
        }

        List<TransportOrder> orders = orderMapper.selectList(queryWrapper);
        
        if (orders.isEmpty()) {
            throw new RuntimeException("未找到可发车的订单");
        }

        // 批量更新订单状态
        LambdaUpdateWrapper<TransportOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TransportOrder::getId, orders.stream().map(TransportOrder::getId).collect(Collectors.toList()))
                .set(TransportOrder::getOrderStatus, Constants.OrderStatus.TRANSPORTING)
                .set(TransportOrder::getDispatchedAt, LocalDateTime.now());

        return orderMapper.update(null, updateWrapper);
    }

    /**
     * 撤销发车操作
     */
    @Transactional
    public int cancelDispatch(Long vehicleId) {
        String currentUserRole = getCurrentUserRole();
        Long currentSiteId = SiteContextHolder.getSiteId();

        // 查询该车辆的所有TRANSPORTING状态订单
        LambdaQueryWrapper<TransportOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TransportOrder::getVehicleId, vehicleId)
                .eq(TransportOrder::getOrderStatus, Constants.OrderStatus.TRANSPORTING);

        // 站点隔离
        if ("SITE_ADMIN".equals(currentUserRole) && currentSiteId != null) {
            queryWrapper.eq(TransportOrder::getSiteId, currentSiteId);
        }

        List<TransportOrder> orders = orderMapper.selectList(queryWrapper);
        
        if (orders.isEmpty()) {
            throw new RuntimeException("未找到可撤销发车的订单");
        }

        // 批量更新订单状态
        LambdaUpdateWrapper<TransportOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TransportOrder::getId, orders.stream().map(TransportOrder::getId).collect(Collectors.toList()))
                .set(TransportOrder::getOrderStatus, Constants.OrderStatus.LOADED)
                .set(TransportOrder::getDispatchedAt, null);

        return orderMapper.update(null, updateWrapper);
    }

    /**
     * 转换订单信息
     */
    private DispatchVehicleInfo.DispatchOrderInfo convertToOrderInfo(TransportOrder order) {
        DispatchVehicleInfo.DispatchOrderInfo orderInfo = new DispatchVehicleInfo.DispatchOrderInfo();
        orderInfo.setOrderId(order.getId());
        orderInfo.setOrderNumber(order.getOrderNo());
        orderInfo.setPickupAddress(order.getDepartureSiteName()); // 发货站点作为取货地址
        orderInfo.setDeliveryAddress(order.getReceiverAddress());
        orderInfo.setCustomerName(order.getSenderName());
        orderInfo.setCustomerPhone(order.getSenderPhone());
        orderInfo.setLoadedAt(order.getLoadedAt());
        return orderInfo;
    }

    /**
     * 获取当前用户角色
     */
    private String getCurrentUserRole() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                Object roleObj = request.getAttribute("role");
                if (roleObj != null) {
                    return roleObj.toString();
                }
            }
        } catch (Exception e) {
            // 忽略异常
        }
        return null;
    }
}
